<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Demo</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #messages { border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; height: 200px; overflow-y: scroll; }
        #inputMessage { width: 80%; }
        #sendButton { width: 18%; }
    </style>
</head>
<body>

<h1>WebSocket Demo</h1>

<div id="messages"></div>
<input type="text" id="inputMessage" placeholder="输入消息...">
<button id="sendButton">发送</button>

<script>
    const userId = 123; // 用户 ID
    const token = 'b2109e33-7a72-4c1a-8abb-fa106bc9bd38'; // 替换为你的 Access Token
    const socket = new WebSocket(`ws://127.0.0.1:1001/chat/${userId}?Access-Token=${token}`);

    // 连接成功时
    socket.onopen = function(event) {
        console.log("WebSocket 连接成功");
        document.getElementById("messages").innerHTML += "<p>连接成功</p>";
    };

    // 接收到消息时
    socket.onmessage = function(event) {
        console.log("收到消息: " + event.data);
        document.getElementById("messages").innerHTML += "<p>收到: " + event.data + "</p>";
    };

    // 连接关闭时
    socket.onclose = function(event) {
        console.log("WebSocket 连接关闭");
        document.getElementById("messages").innerHTML += "<p>连接关闭</p>";
    };

    // 发生错误时
    socket.onerror = function(event) {
        console.error("WebSocket 发生错误: ", event);
    };

    // 发送消息
    document.getElementById("sendButton").onclick = function() {
        const message = document.getElementById("inputMessage").value;
        if (message) {
            socket.send(message);
            document.getElementById("messages").innerHTML += "<p>发送: " + message + "</p>";
            document.getElementById("inputMessage").value = ""; // 清空输入框
        }
    };
</script>

</body>
</html>

